package com.beit.mybatis.demo.common.component;

import com.beit.mybatis.demo.common.model.CustomProblemDetail;
import jakarta.servlet.RequestDispatcher;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;

@ControllerAdvice
public class CustomControllerAdvice extends ResponseEntityExceptionHandler {

    @Value("${spring.mvc.problemdetails.enabled:false}")
    private Boolean problemDetailsEnabled;

    @ResponseBody
    @ExceptionHandler(RuntimeException.class)
    public ResponseEntity<?> handleIllegalArgumentException(HttpServletRequest request, Throwable throwable) {
        HttpStatus status = getStatus(request);
        CustomProblemDetail problemDetail = new CustomProblemDetail(status.value());
        problemDetail.setDetail(throwable.getMessage());
        if (Boolean.TRUE.equals(problemDetailsEnabled)) {
            problemDetail.setProperty("stackTrace", throwable.getStackTrace());
        }
        return new ResponseEntity<>(problemDetail, status);
    }

    private HttpStatus getStatus(HttpServletRequest request) {
        Integer statusCode = (Integer) request.getAttribute(RequestDispatcher.ERROR_STATUS_CODE);
        if (statusCode == null) {
            return HttpStatus.INTERNAL_SERVER_ERROR;
        }
        try {
            return HttpStatus.valueOf(statusCode);
        }
        catch (Exception ex) {
            return HttpStatus.INTERNAL_SERVER_ERROR;
        }
    }
}
